const { code } = require('../static/secret')
const json = require('jsonwebtoken')
const multer = require('@koa/multer')
const fs = require('fs-extra')
// const pa = require('path')

const storage = multer.diskStorage({
  destination: async function (ctx, file, cb) {
    const token = ctx.headers.authorization.split(' ')[1]
    const info = await json.verify(token, code)
    const answer = await fs.pathExists(`./upload/${info.username}`)
    if (!answer) {
      fs.mkdirsSync(`./upload/${info.username}`)
    }
    cb(null, './upload/' + info.username)
  },
  async filename (ctx, file, cb) {
    console.log(file)
    const token = ctx.headers.authorization.split(' ')[1]
    const info = await json.verify(token, code)
    const answer = await fs.pathExists(`./upload/${info.username}/${file.originalname}`)
    if (!answer) {
      cb(null, file.originalname)
    } else {
      cb(new Error('文件名重复'))
    }
  }
})

module.exports = multer({ storage })
